<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card>
      <el-form :inline="true" :model="listQuery" size="small">
        <!-- <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >
            新增{{ title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>

      <!-- table列表 -->
      <el-table
        style="width: 100%"
        border
        stripe
        size="small"
        :data="datas"
        v-loading="listLoading"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="#" align="center" type="selection" />
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.align : 'center'"
          :width="column.width ? column.width : ''"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getRoleList"
      />
    </el-card>
    <!-- 弹框 -->
    <el-dialog
      :title="getTitle"
      :visible.sync="dialogVisible"
      width="50%"
      @close="handleClose"
    >
      <el-form
        size="small"
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="width: 95%"
      >
        <el-form-item label="角色名" prop="name">
          <el-input v-model="form.name" placeholder="角色名" clearable />
        </el-form-item>
        <el-form-item label="角色说明" prop="comment">
          <el-input v-model="form.comment" placeholder="角色说明" clearable>
          </el-input>
        </el-form-item>
        <el-table
          style="width: 100%"
          border
          stripe
          size="small"
          :data="perms"
          ref="permsRef"
          highlight-current-row
          @selection-change="handlePermSelChange"
        >
          <el-table-column label="#" align="center" type="selection" />
          <el-table-column label="权限名称" prop="name" align="left">
          </el-table-column>
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="handleSave(false)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";

import {
  getRoles,
  addRole,
  updateRole,
  delRole,
  delRoles,
  getAllRetailer,
  getAllPerms,
} from "@/api/member";

const defaultForm = {
  id: null,
  retailer: null,
  name: null,
  comment: null,
  permissions: [],
};

export default {
  name: "Role",
  data() {
    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        name: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
        retailer: [{ required: true, message: "请选择商家", trigger: "blur" }],
      },
      title: "角色",
      dialogType: "new",
      dialogVisible: false,

      datas: [],
      selections: [],
      selPerms: [],

      perms: [],

      listLoading: true,
      listQuery: {
        retailer_id: null,
        page: 1,
        page_size: 15,
      },
      total: 0,

      tableColumns: [
        {
          key: "name",
          title: "角色名",
          align: "left",
          width: "120px"
        },
        {
          key: "perms",
          title: "权限",
          align: "left",
        },
        {
          key: "comment",
          title: "角色说明",
          align: "left",
        },
        
      ],
    };
  },
  components: {
    Pagination,
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `修改${this.title}`;
    },
  },
  mounted() {
    this.getRoleList();
    this.getPermsList();
  },
  methods: {
    handleClose() {
      this.$refs.permsRef.clearSelection();
    },

    getPermsList() {
      getAllPerms()
        .then((res) => {
          this.perms = res;
          console.log(this.perms);
        })
        .catch((error) => {
          console.log(error);
        });
    },

    getRoleList() {
      this.listLoading = true;
      getRoles(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败!");
        });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getRoleList();
    },
    //添加
    handleAdd() {
      this.dialogVisible = true;
      this.dialogType = "new";
      this.selPerms = [];
      this.form = Object.assign({}, defaultForm);
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    //修改
    handleEdit(scope) {
      this.dialogType = "edit";
      this.form = scope.row;
      const arr_perms = this.form.permissions;

      const filter_perms = this.perms.filter((item) => {
        return arr_perms.includes(item.id);
      });

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
        filter_perms.forEach((item) => {
          this.$refs.permsRef.toggleRowSelection(item, true);
        });
      });
    },
    //确定添加数据
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;
        this.form.permissions = this.selPerms;
        if (this.dialogType == "new") {
          try {
            res = await addRole(this.form);
          } catch (err) {
            this.$message.error("增加失败!");
          }
        } else {
          try {
            res = await updateRole(this.form);
          } catch (err) {
            this.$message.error("修改失败!");
          }
        }

        this.dialogVisible = false;
        this.getRoleList();

        const { name, comment } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>角色名: ${name}</div>
              <div>角色说明: ${comment}</div>
            `,
          type: "success",
        });
      });
    },
    //弹窗显示，数据回显

    //删除数据
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delRole(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delRoles(sel_ids);
          this.getRoleList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },
    handlePermSelChange(val) {
      this.selPerms = val.map((item) => item.id);
    },
  },
};
</script>

<style scoped>
</style>